<?php

namespace App\Admin\Metrics\Examples;

use App\Handlers\KeysHandler;
use App\Models\User;
use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class NewShops extends Line
{
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();

        $this->title('新增店铺');
        $this->dropdown([
            '1' => '过去1天',
            '7' => '过去7天',
            '15' => '过去15天',
            '30' => '过去一个月'
        ]);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return void
     */
    public function handle(Request $request)
    {
        $data = $this->data($request->get('option', 7));
        $this->withContent($data['total'] ?? 0);
        // 图表数据
        $this->withChart($data['list']);
    }


    protected function data($days = 7)
    {
        return Cache::remember(sprintf(KeysHandler::NEW_USERS_SHOP, $days), now()->endOfDay(), function () use ($days) {
            $users = User::query()->where('state','=',User::STATE_PASS)->whereBetween('shop_created_at', [now()->subDays($days + 1)->startOfDay(), now()->subDay()->endOfDay()])->select('shop_created_at')->get();
            $list = [];
            for ($i = $days; $i > 0; $i--) {
                $list[] = $users->where('state','=',User::STATE_PASS)->whereBetween('shop_created_at', [now()->subDays($i)->startOfDay(), now()->subDays($i)->endOfDay()])->count();
            }
            $data['list'] = $list;
            $data['total'] = count($users);
            return $data;
        });
    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => [
                [
                    'name' => $this->title,
                    'data' => $data,
                ],
            ],
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent(string $content)
    {
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">$content</h2>
    <span class="mb-0 mr-1 text-80">$this->title</span>
</div>
HTML
        );
    }
}
